<template>
  <div class="login">
    <!-- 顶部 -->
    <div class="main-t">
      <!-- 导航栏 -->
      <div class="banner">
        <van-nav-bar>
          <template #left>
            <van-icon name="arrow-left" color="black" @click="back" />
          </template>
        </van-nav-bar>
      </div>
    </div>
    <!-- 中部 -->
    <div class="main-c">
      <div class="tag">请输入账号密码</div>
      <div class="login-input">
        <div class="login-input-box">
          <van-cell-group inset>
            <van-field v-model="username" clearable placeholder="账号(最多15字符)" maxlength="15" />
          </van-cell-group>
        </div>
        <div class="login-input-box">
          <van-cell-group inset>
            <van-field v-model="password" clearable type="password" placeholder="密码(最多15字符)" maxlength="15" />
          </van-cell-group>
        </div>
      </div>
    </div>
    <!-- 底部 -->
    <div class="main-b">
      <div class="fixedBtn" @click="login()">登录</div>
      <div class="register-box">
        没有账号进行 <b @click="toRegister">注册</b>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="Login">
// 登录页面
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStorage } from '@vueuse/core'
import request from '@/utils/request';
import { showLoadingToast, showSuccessToast, showFailToast } from 'vant'


const router = useRouter()
function back() {
  router.go(-1)
}

let username = ref("admin")
let password = ref("123456")

async function login() {
  // 加载提示
  showLoadingToast({
    message: '登录中...',
    forbidClick: true,
  })

  // 请求
  console.log('你好')
  try {
    const response = await request.login({
      username: username.value,
      password: password.value
    }).then(res => {
      console.log(res)
      const resData:any = res
      const data = res.data

      // 登录成功
      if (resData.code == 1) {
        // 存储token，跳转到首页
        showSuccessToast('登录成功')
        localStorage.setItem('account',JSON.stringify({
          id: data.id,
          token: data.token + '',
          name: data.name,
          userName: data.userName
        }))
        router.push("/home") // 跳转到首页
      } else {
        showFailToast('登录失败: ' + data.msg)
      }
    })
  } catch (error) {
    console.error('请求出错:', error);
  }
}

function toRegister() {
  router.push('/register')
  console.log('注册')
}

</script>

<style scoped lang="less">
@gabelMargin : 30px; // 全局margin
@gabelBgColor : rgb(181, 202, 161);
@garyFontColor : rgb(125, 125, 125);
@grayBgColor: rgb(240, 240, 240);

.login {
  height: 100vh;
}

.main-c {
  margin: @gabelMargin;

  .tag {
    font-size: 50px;
    margin-bottom: 60px;
  }
}

.login-input-box {
  margin: 25px -15px;
}

.van-cell {
  background-color: @grayBgColor;
  border-radius: 50px;

  ::placeholder {
    color: gray;
  }
}

.fixedBtn {
  position: relative;
  margin-top: 60px;
}

.register-box {
  margin: @gabelMargin;
  font-size: 30px;
}

b {
  color: @gabelBgColor;
}
</style>